﻿app.controller('LoginController', function ($scope, $rootScope, $http, $location, userFactory, base64Factory, groupRoleFactory, signupFactory) {

    init();

    //all implement data model call in a init() function
    function init() {
        $scope.fileSever = mainFileAddress;
        if (localStorage.getItem('idkey') != null) {
            $location.path('/notification');
        }

        $scope.acc = { UserName: null, Password: null };
        $scope.login = function () {
            var authen = 'Basic ' + base64Factory.encode($scope.acc.UserName + ':' + $scope.acc.Password);
            userFactory.login(authen).success(function (data) {
                if (data != null && data != "null") {
                    localStorage.setItem("idkey", data.Id);
                    localStorage.setItem("authen", authen);
                    $rootScope.userName = $scope.acc.UserName;
                    //------------load menu role---------

                    groupRoleFactory.getRoleByGroup(data.GroupId).success(function (datarole) {
                        $scope.roleByGroup = datarole;
                        if (localStorage.getItem("menu") == null) {
                            localStorage.setItem("menu", JSON.stringify(datarole));
                        }
                        $location.path('/notification');
                    });
                } else {
                    alert("Đăng nhập không thành công!");
                }
            }).error(function () {
                alert("Đăng nhập không thành công!");
            });
        };
        $scope.lostPassClick = function () {
            $scope.lostPass = !$scope.lostPass;
        };
        $scope.sendPassToEmail = function () {
            signupFactory.sendPass({ Text: $("#lostpass").val() }).success(function () {
                $("#lostpassStatus").html("Mật khẩu đã gửi về email!");
            }).error(function () {
                $("#lostpassStatus").html("Xảy ra lỗi");
            });;
        };
        $scope.activeAccountClick = function () {
            $scope.activeAccount = !$scope.activeAccount;
        };
        $scope.active = function () {
            signupFactory.acctiveAccount($("#activeacc").val()).success(function(data) {
                $("#activeStatus").html(data);
            }).error(function (data) {
                $("#activeStatus").html(data);
            });
        };
    }
});